package cj.web.admin.controllers;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import net.paoding.rose.web.annotation.Param;
import net.paoding.rose.web.annotation.Path;
import net.paoding.rose.web.annotation.rest.Get;
import net.paoding.rose.web.annotation.rest.Post;
import net.paoding.rose.web.var.Model;
import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

import cj.utils.Constants;
import cj.utils.MD5Security;
import cj.web.admin.dao.AreaDAO;
import cj.web.admin.dao.GameDAO;
import cj.web.admin.dao.PermitConfigDAO;
import cj.web.admin.dao.PermitDAO;
import cj.web.admin.dao.SchoolDAO;
import cj.web.admin.domain.Area;
import cj.web.admin.domain.Game;
import cj.web.admin.domain.Permit;
import cj.web.admin.domain.PermitConfig;
import cj.web.admin.domain.School;
import cj.web.admin.util.StringRandom;
import cj.web.constants.GameTypeEnum;
import cj.web.constants.MemuEnum;
import cj.web.constants.PermitStatusEnum;
import cj.web.login.controllers.BaseController;

@Path("/permitConfig")
public class PermitConfigController extends BaseController{

	private static Logger logger = Logger.getLogger(PermitConfigController.class.getName());
	
	@Autowired
	private PermitConfigDAO permitConfigDao;
	@Autowired
	private AreaDAO areaDao;
	@Autowired
	private SchoolDAO schoolDao;
	@Autowired
	private GameDAO gameDao;
	@Autowired
	private PermitDAO permitDao;
	
	@Get("show")
	public String show(Model model,PermitConfig permitConfig) {
		
		List<Area> arealis = areaDao.queryAll();
		model.add("arealis",arealis);
		//MemuEnum
        model.add("MemuEnum",MemuEnum.cszp);
		return "/views/game/permitConfigList.vm";
	}

	@Post("getList")
	public String queryList(PermitConfig permitConfig) {
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		
		List<PermitConfig> objs = permitConfigDao.query(permitConfig);
		int size = permitConfigDao.querySize(permitConfig);
		
		jo.put("data", objs);
		jo.put("draw", permitConfig.getDraw());
		jo.put("recordsTotal", size);
		jo.put("recordsFiltered", size);
		return "@"+jo.toString();
	}
	
	@Get("createPage")
	public String createPage(Model model) {
		List<Area> arealis = areaDao.queryAll();
		model.add("arealis",arealis);
		
		List<School> schoollis = schoolDao.queryAll();
		model.add("schoollis",schoollis);
		//MemuEnum
        model.add("MemuEnum",MemuEnum.cszp);
		return "/views/game/permitConfigDetail.vm";
	}
	
	@Post("create")
	public String create(Model model,@Param("areaId")int areaId,@Param("schoolId")int schoolId,
			@Param("roomNo")List<Integer> roomNo,@Param("seatNo")List<Integer> seatNo,
			@Param("sequence")List<Integer> sequence,HttpServletRequest request) {
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		
		Area areaObj = areaDao.queryById(areaId);
		School schoolObj = schoolDao.queryById(schoolId);
		
		try {
			for(int i=0;i<roomNo.size();i++){
				PermitConfig permitConfig = new PermitConfig();
				permitConfig.setAreaId(areaObj.getId());
				permitConfig.setAreaCode(areaObj.getCode());
				permitConfig.setAreaName(areaObj.getName());
				permitConfig.setSchoolId(schoolObj.getId());
				permitConfig.setSchoolCode(schoolObj.getCode());
				permitConfig.setSchoolName(schoolObj.getName());
				permitConfig.setSchoolAddress(schoolObj.getAddress());
				
				permitConfig.setRoomNo(roomNo.get(i));
				permitConfig.setSeatNo(seatNo.get(i));
				permitConfig.setSequence(sequence.get(i));
				
				//计算学校考试人数=教室号*座位号
				int schoolNum = roomNo.get(i)*seatNo.get(i);
				permitConfig.setSchoolNum(schoolNum);
				
				permitConfig.setDeleteFlag(Constants.deleteFlag.deleteFlag_1);
				permitConfig.setCreateUser(returnSessionObj(request).getAccount());
				permitConfig.setUpdateUser(returnSessionObj(request).getAccount());
				
				permitConfigDao.create(permitConfig);
			}
			
		} catch (Exception e) {
			// TODO: handle exception
			jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
		}
		
		return "@"+jo.toString();
	}
	
	@Get("edit")
	public String edit(Model model,@Param("id") int id) {
		PermitConfig obj = permitConfigDao.queryById(id);
		model.add("obj", obj);
		
		List<Area> arealis = areaDao.queryAll();
		model.add("arealis",arealis);
		
		List<School> schoollis = schoolDao.queryAll();
		model.add("schoollis",schoollis);
		//MemuEnum
        model.add("MemuEnum",MemuEnum.cszp);
		return "/views/game/permitConfigEdit.vm";
	}
	
	@Post("update")
	public String update(Model model,PermitConfig permitConfig,HttpServletRequest request) {
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		
		try {
			Area areaObj = areaDao.queryById(permitConfig.getAreaId());
			School schoolObj = schoolDao.queryById(permitConfig.getSchoolId());
			
			permitConfig.setAreaId(areaObj.getId());
			permitConfig.setAreaCode(areaObj.getCode());
			permitConfig.setAreaName(areaObj.getName());
			permitConfig.setSchoolId(schoolObj.getId());
			permitConfig.setSchoolCode(schoolObj.getCode());
			permitConfig.setSchoolName(schoolObj.getName());
			permitConfig.setSchoolAddress(schoolObj.getAddress());
			
			//计算学校考试人数=教室号*座位号
			int schoolNum = permitConfig.getRoomNo()*permitConfig.getSeatNo();
			permitConfig.setSchoolNum(schoolNum);
			
			permitConfig.setUpdateUser(returnSessionObj(request).getAccount());
			permitConfigDao.update(permitConfig);
		} catch (Exception e) {
			// TODO: handle exception
			jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
		}
		
		return "@"+jo.toString();
	}
	
	@Get("deleteById")
	public String deleteById(Model model,@Param("id") int id) {
		permitConfigDao.deleteById(id);
		return "r:show";
	}
	
	/**
	 * 
	 * @param model
	 * @return
	 */
	@Get("permitCreatePage")
	public String permitCreatePage(Model model) {
		List<Map> objs = gameDao.asGameEnum(Integer.parseInt(GameTypeEnum.FF.getValue()));
		model.add("gameObjs", objs);
		//MemuEnum
        model.add("MemuEnum",MemuEnum.cszpsc);
		return "/views/game/permitCreateList.vm";
	}
	
	/**
	 * 重新生成
	 * @param model
	 * @param gameId
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@Get("initPermitByGId")
	public String initPermitByGId(Model model,@Param("gameId") int gameId,HttpServletRequest request) throws Exception{
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		
		try {
			Game obj = gameDao.queryById(gameId);
			if(obj!=null){
				permitDao.removeByGId(gameId);
				
				List<Area> arealis = areaDao.queryAll();
				List<School> schoollis = schoolDao.queryAll();
				
				for(School schoolObj:schoollis){
					returnCode(arealis, schoollis, gameId, schoolObj.getAreaId(), schoolObj.getId(), request);
				}
			}
		} catch (Exception e) {
			// TODO: handle exception
			jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
		}
		
		return "@"+jo.toString();
	}
	
	//---------------------------------------------------------生成参赛证号new
	/**
	 * 生成回执码
	 * @param arealis		区域lis
	 * @param schoollis		学校lis
	 * @param gameId		活动ID
	 * @param areaId		区域ID
	 * @param schoolId		学校ID
	 * @param request		
	 */
	private void returnCode(List<Area> arealis,List<School> schoollis,int gameId,
			int areaId,int schoolId,HttpServletRequest request) {
		//参赛证配置表
		List<PermitConfig> permitConfigLis = permitConfigDao.queryListById(areaId, schoolId);
		
		int totalSchoolNum=0;//总人数
		int totalRoomNo=0;//总教室数
		String returnCode = "";//回执码
		for(int i=0;i<permitConfigLis.size();i++){
			
			//房间数
			int roomNos = permitConfigLis.get(i).getRoomNo();
			//座位数
			int seatNos = permitConfigLis.get(i).getSeatNo();
			
			for(int roomNo=0;roomNo<roomNos;roomNo++){
				totalRoomNo++;
				for(int seatNo=1;seatNo<=seatNos;seatNo++){
					totalSchoolNum++;
					
					//区域Code
					String areaCode = permitConfigLis.get(i).getAreaCode();
					//区域areaName
					String areaName = permitConfigLis.get(i).getAreaName();
					//学校Code
					String schoolCode = permitConfigLis.get(i).getSchoolCode();
					//学校Code
					String schoolName = permitConfigLis.get(i).getSchoolName();
					//学校Code
					String address = permitConfigLis.get(i).getSchoolAddress();
					//教室Code
					String roomCode = StringRandom.formatNum("00", totalRoomNo);
					//座位Code
					String seatCode = StringRandom.formatNum("000", seatNo);
					//回执码
					returnCode = areaCode+schoolCode+roomCode+seatCode;
					
					//参赛证号
					String permitCode = areaCode+schoolCode+StringRandom.formatNum("0000", totalSchoolNum);
					//创建参赛证号
					createPermitCode(areaName, areaId, schoolId, schoolName, address, permitCode, returnCode, gameId, request);
				}
			}
		}
	}
	
	/**
	 * 生成参赛证号
	 * @param arealis		地址
	 * @param schoollis		学校
	 * @param permitCode	参赛证
	 * @param returnCode	回执码
	 * @param gameId		活动ID
	 * @param request		
	 */
	private void createPermitCode(String areaName,int areaId,int schoolId,String schoolName,
			String address,String permitCode,String returnCode,int gameId,HttpServletRequest request){
		try {
//			for(Area areaObj:arealis){
//				int areaId = areaObj.getId();//区域ID
//				String areaName = areaObj.getName();//区域名称
//				for(School schoolObj:schoollis){
					//学校属于区域
//					if(areaId==schoolObj.getAreaId()){
//						int schoolId = schoolObj.getId();//学校ID
//						String schoolName = schoolObj.getName();//学校名称
//						String address = schoolObj.getAddress();//学校名称
						
						//检索参赛证号判断是否存在
						Permit permitObj =permitDao.queryByCode(permitCode, gameId);
						if(permitObj==null){
							//不存在参赛证号
							String pwd = StringRandom.getSixRandom();//密码
							
							Permit permit = new Permit();
							permit.setAreaName(areaName);
							permit.setAreaId(areaId);
							permit.setCode(permitCode);
							permit.setGameId(gameId);
							permit.setSchoolId(schoolId);
							permit.setSchoolName(schoolName);
							permit.setAddress(address);
							permit.setPwd(MD5Security.md5(pwd));
//							permit.setPwdShow(Base64.getBase64(pwd));
							permit.setPwdShow(pwd);
							permit.setReturnCode(returnCode);
							permit.setStatus(PermitStatusEnum.YXWSY.getValue());
							permit.setCreateUser(returnSessionObj(request).getAccount());
							permit.setUpdateUser(returnSessionObj(request).getAccount());
							permitDao.create(permit);
						}
//					}
//				}
//			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
	}
}